package main

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx context.Context
	dev DeviceHT
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
	listen, err := net.Listen("tcp", "0.0.0.0:1234")
	if err != nil {
		log.Fatal(err)
		return
	}
	defer listen.Close()
	runtime.LogInfo(a.ctx, "listen on 1234")

	conn, err := listen.Accept()
	if err != nil {
		log.Fatal(err)
		return
	}
	go a.process(conn)
}

func (a *App) process(conn net.Conn) {
	defer conn.Close()
	for {
		reader := bufio.NewReader(conn)
		var buf [512]byte
		n, err := reader.Read(buf[:])
		if err != nil {
			log.Println("read from client failed err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println("收到client发送的数据:", recvStr)
		err = json.Unmarshal([]byte(recvStr), &a.dev.Real_ht_array)
		if err != nil {
			log.Println(err)
			continue
		}
		log.Println("go parse json", a.dev.Real_ht_array.H, a.dev.Real_ht_array.T)
		runtime.EventsEmit(a.ctx, "real_data", recvStr)
	}
}

func (a *App) GetHT() (H, T float32) {
	return a.dev.Real_ht_array.H, a.dev.Real_ht_array.T
}
